﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
using MSWord = Microsoft.Office.Interop.Word;

namespace ExcelCharCount
{
    public partial class Form1 : Form
    {

        public const int WM_NCLBUTTONDOWN = 0xA1;
        public const int HT_CAPTION = 0x2;

        [DllImportAttribute("user32.dll")]
        private static extern int SendMessage(IntPtr hWnd,
                         int Msg, int wParam, int lParam);
        [DllImportAttribute("user32.dll")]
        private static extern bool ReleaseCapture();

        private static int WM_HOTKEY = 0x0312;

        /// <summary>
        /// The enumeration of possible modifiers.
        /// </summary>
        [Flags]
        public enum ModifierKeys : uint
        {
            Alt = 1,
            Control = 2,
            Shift = 4,
            Win = 8
        }
        // Registers a hot key with Windows.
        [DllImport("user32.dll")]
        private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);
        // Unregisters the hot key with Windows.
        [DllImport("user32.dll")]
        private static extern bool UnregisterHotKey(IntPtr hWnd, int id);

        enum HotKeys : int
        {
            ExcelToWord = 1,
            WordToExcel
        }
        public Form1()
        {
            InitializeComponent();
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            RegisterHotKey(this.Handle, (int)HotKeys.ExcelToWord, (uint)(ModifierKeys.Win | ModifierKeys.Control), (uint)Keys.W);
            RegisterHotKey(this.Handle, (int)HotKeys.WordToExcel, (uint)(ModifierKeys.Win | ModifierKeys.Control), (uint)Keys.E);

            MessageBox.Show("Ctrl-Win-W: Copy to Word\nCtrl-Win-E: Copy to Excel");
        }
        protected override void WndProc(ref Message m)
        {
            // check if we got a hot key pressed.
            if (m.Msg == WM_HOTKEY)
            {
                switch ((HotKeys)m.WParam.ToInt32())
                {
                    case HotKeys.ExcelToWord:
                        ExcelToWord();
                        break;
                    case HotKeys.WordToExcel:
                        WordToExcel();
                        break;
                }
            }
            base.WndProc(ref m);
        }

        private void WordToExcel()
        {
            var excel = GetExcelApp();
            var word = GetWordApp();

            if ((excel == null) || (word == null))
            {
                MessageBox.Show("Start Word and Excel first!");
                return;
            }


            var text = word.ActiveDocument.Range().Text;
            if (MessageBox.Show(string.Format("Copy {0} chars to excel?", text.Length), null, MessageBoxButtons.OKCancel) != System.Windows.Forms.DialogResult.OK)
                return;

            var cell = excel.ActiveCell;
            if (cell == null)
            {
                MessageBox.Show("No active cell!");
                return;
            }
            cell.Value = text;
            excel.ActiveWindow.Activate();
            excel.Visible = true;
        }

        private void ExcelToWord()
        {
            var excel = GetExcelApp();
            var word = GetWordApp();

            if ((excel == null) || (word == null))
            {
                MessageBox.Show("Start Word and Excel first!");
                return;
            }
            if (excel.ActiveCell == null)
            {
                MessageBox.Show("No active cell!");
                return;
            }
            var text = excel.ActiveCell.Text;
            word.ActiveDocument.Range().Text = text;
            word.Activate();
            word.ActiveDocument.CheckGrammar();

        }

        private MSWord.Application GetWordApp()
        {
            try
            {
                return Marshal.GetActiveObject("Word.Application") as MSWord.Application;
            }
            catch
            {
                return null;
            }
        }

        private Excel.Application GetExcelApp()
        {
            try
            {
                return Marshal.GetActiveObject("Excel.Application") as Excel.Application;
            }
            catch
            {
                return null;
            }
        }
        private void Update()
        {
            Excel.Application app = GetExcelApp();
            if (app == null)
            {
                label1.Text = "Start Excel";
                return;
            }

            var cell = app.ActiveCell;
            if (cell == null)
            {
                label1.Text = "n/a";
                return;
            }
            string text = cell.Text.ToString();
            label1.Text = string.Format("{0}: {1:0000}C", cell.Address, text.Length);
        }

        private void label1_Click(object sender, EventArgs e)
        {
            Update();
        }

        private void Form1_MouseDown(object sender, MouseEventArgs e)
        {

        }

        private void label1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                Update();
                ReleaseCapture();
                SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            Update();
        }
    }
}
